package helper

import (
	"crypto/md5"
	"encoding/hex"
	"golang.org/x/crypto/bcrypt"
	"math/rand"
	"time"
)

func RandString(length int) string {
	bytes := []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
	var result []byte
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < length; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

func MD5hash(str ...string) string {
	md5Ctx := md5.New()
	for _, v := range str {
		md5Ctx.Write([]byte(v))
	}
	return hex.EncodeToString(md5Ctx.Sum(nil))
}

func EncodePassword(source string) string {
	// Hashing the password with the default cost of 10
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost)
	if err != nil {
		return ""
	}
	return string(hashedPassword)

}

func ComparePassword(hashedPassword, password string) error {
	// Comparing the password with the hash
	return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
	// nil means it is a match
}
